var app = getApp();
var maxPageIndex;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    ifShowTips: true,
    ifShownoData: true,
    wOrderVo: "",
    countNum: 0,//今日接单数
    totalPrice: 0,//今日总金额
    buthiddenPrice: false,
    buthiddenTel: false,
    buthiddenCancel: false,
    buthiddenV: false,
    userId: "",
    userInfo: null,
    code: "",
    //openId:"",
    wxType: "",
    orderStatus: [

      {
        "statusName": "进行中",
        "statusCode": 1
      },
      {
        "statusName": "所有订单",
        "statusCode": ""
      }

    ],

    statusSelect: 1,//判断是否选中
    pageIndex: 1,
    auditStatus: 3,//认证成功
    ifShowV: true,
    ifClick: true,
    ifbuthiddenV: true,
    flag: 0,
    checks: [],
    comment: "匿名评价用户",
    arrayChecks: "",
    userid: "",//下单用户id
    sendUserid: "",//接单回收员id
    orderid: "",
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    if (options.finish) {
      that.setData({ statusSelect: "" });
    }

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        that.data.code = res.code;
        var code = res.code;
        wx.request({
          method: "POST",
          url: 'https://www.zaishengwang.com/wx/toCheckUser.do',
          dataType: 'json',
          header: {
            'content-type': 'application/x-www-form-urlencoded;',
          },
          data: {
            code: code,
          },
          success: function (res) {
            if (res.data.userVo == null) {
              app.globalData.openId = res.data.openId
              wx.reLaunch({
                url: '../register/register',
              })
            } else {
              that.data.userId = res.data.userVo.bId;
              app.globalData.wxType = res.data.userVo.wxType;
              that.setData({ wxType: app.globalData.wxType });
              wx.setStorageSync('userId', res.data.userVo.bId);
              var userId = wx.getStorageSync('userId');
              if (userId != "") {
                app.globalData.userId = userId;
                app.globalData.openId = res.data.openId;
                that.setData({ ifShowTips: true });
                that.onMineInfo();
                that.onTodayInfo();
                that.onOrderInfo();

              } else {
                that.setData({ ifShowTips: false });
              }

            }
          },
          fail: function (error) {

          }
        })
      }
    })

    // var userId = wx.getStorageSync('userId');

    // that.setData({ userId: userId});
    // app.globalData.userId = userId;

    // 查看是否授权
    // wx.getSetting({
    //   success: function (res) {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称
    //       wx.getUserInfo({
    //         success:function(res){
    //           console.log(res.userInfo);
    //         }
    //       })
    //     }
    //   }
    // })  


  },

  orderStatusList: function (e) {
    var that = this;
    that.setData({//把选中值放入判断值
      statusSelect: e.currentTarget.dataset.select,
      pageIndex: 1,
      wOrderVo: " ",
    })
    that.onOrderInfo();
  },

  //订单详情页
  goOrderDetail:function(e){
    var bId = e.currentTarget.dataset.bid;
    wx.navigateTo({
      url: 'order_detail?bId=' + bId,
    })
  },
  

  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.onOrderInfo();
  },
  //扫一扫
  goscan: function () {
    wx.scanCode({
      onlyFromCamera: false,
      scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'],
      success: (res) => {
        var userId = res.result;
        var receiptId = app.globalData.userId;
        if (userId.length == receiptId.length) {
          if (userId != receiptId) {
            wx.request({
              method: "POST",
              url: 'https://www.zaishengwang.com/wx/toScanOrder.do',
              dataType: 'json',
              header: {
                'content-type': 'application/x-www-form-urlencoded;',
              },
              data: {
                userId: userId,
                receiptId: receiptId,
              },
              success: function (res) {
                //console.log("receiptId", res);
                if (res.data.msg == "1") {
                  wx.navigateTo({
                    url: 'scan?bId=' + res.data.orderVo.bId,
                  })
                }
              },
              fail: function (error) {
                console.log("error", error);
              }
            })
          } else {
            wx.showModal({
              title: '不符合该系统规定的用户！',
              confirmColor: '#56BDE0',
              showCancel: false,
            })
          }

        } else {
          wx.showModal({
            title: '不符合该系统规定的二维码！',
            confirmColor: '#56BDE0',
            showCancel: false,
          })
        }


      },
      fail: (res) => {
        console.log("fail", res);
        wx.showModal({
          title: '不符合该系统规定的二维码！',
          confirmColor: '#56BDE0',
          showCancel: false,
        })
      }
    })

  },
  //二维码
  goCode: function () {

    wx.navigateTo({
      url: 'code',
    })

  },

  goSetting: function () {

    wx.navigateTo({
      url: '../mine/accountSetting',
    })

  },

  //去认证
  goAuthentication: function () {

    wx.navigateTo({
      url: '../mine/authentication',
    })

  },

  onMineInfo: function () {
    var that = this;
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toHomeUser.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        id: app.globalData.userId,
      },
      success: function (res) {
        //auditStatus 3认证成功
        that.setData({ auditStatus: res.data.userVo.auditStatus });
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },

  //今日接单，总金额请求接口

  onTodayInfo: function () {
    var that = this;
    wx.showLoading({
      title: '拼命加载中',
      mask: true
    })
    //进行中订单列表信息
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toHomenCount.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        id: app.globalData.userId,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.totalPrice == undefined) {
          that.setData({ countNum: res.data.countNum, totalPrice: 0 })
        } else {
          that.setData({ countNum: res.data.countNum, totalPrice: parseFloat(res.data.totalPrice).toFixed(2) })
        }
      },
      fail: function (error) {
      }
    })
  },

  //订单列表信息
  onOrderInfo: function () {
    var that = this;
    var arr = new Array;
    wx.showLoading({
      title: '拼命加载中',
      mask: true
    })

    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/serchReceiptOrderList.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        receiptId: app.globalData.userId,
        status: that.data.statusSelect,
        page: that.data.pageIndex,
        size: 8
      },
      success: function (res) {
        wx.hideLoading();
        maxPageIndex = res.data.pages.total / 8;
       
        if (res.data.wOrderVo.length > 0) {

          for (var i = 0; i < res.data.wOrderVo.length; i++) {
            let createTime = res.data.wOrderVo[i].createTime.substring(0, 19);
            let countPrice = parseFloat(res.data.wOrderVo[i].countPrice).toFixed(2);
            res.data.wOrderVo[i].createTime = createTime;
            res.data.wOrderVo[i].countPrice = countPrice;
          }
          that.setData({ ifShownoData: true });
          // arr.push((res.data.wOrderVo));
          arr = res.data.wOrderVo;

        } else {
          that.setData({ ifShownoData: false });
         
        }
        
          if (that.data.pageIndex != 1) {
            var array = that.data.wOrderVo;
            array = array.concat(arr);
            that.setData({ ifShownoData: true, wOrderVo: array });
          } else {
            that.setData({ wOrderVo: arr });
          }
       
        
      },
      fail: function (error) {
      },

    })
  },

  bindGetUserInfo: function (e) {
    var that = this;
    that.setData({ ifShowTips: true });
    //使用
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.login({
            success: function (res) {
              var code = res.code;//登录凭证
              if (code) {
                //2、调用获取用户信息接口
                wx.getUserInfo({
                  success: function (res) {
                    var nickName = res.rawData.nickName;
                    var userImg = res.rawData.avatarUrl;
                    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
                    wx.request({
                      url: 'https://www.zaishengwang.com/',//自己的服务接口地址
                      method: 'post',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        code: code,
                        nickName: nickName,
                        userImg: avatarUrl
                      },
                      success: function (data) {

                        //4.解密成功后 获取自己服务器返回的结果
                        if (data.data.status == 1) {
                          var userInfo_ = data.data.userInfo;
                        } else {
                          console.log('解密失败')
                        }

                      },
                      fail: function () {
                        console.log('系统错误')
                      }
                    })
                  },
                  fail: function () {
                    console.log('获取用户信息失败')
                  }
                })

              } else {
                console.log('获取用户登录态失败！' + r.errMsg)
              }
            },
            fail: function () {
              console.log('登陆失败')
            }
          })

        } else {//即点击拒绝授权退出
          wx.navigateBack({
            delta: 1
          })
          console.log('获取用户信息失败')

        }

      }
    })

  },

  //去定价事件
  toPriced: function (e) {
    var that = this;
    var bId = e.currentTarget.dataset.bid;
    var Type = e.currentTarget.dataset.type;
    var paymentStatus = e.currentTarget.dataset.paymentstatus
    that.setData({ buthiddenPrice: true });

    if (paymentStatus == 2) {
      var countPrice = e.currentTarget.dataset.countprice;
      wx.navigateTo({
        url: 'payment?bId=' + bId + '&allTotal=' + countPrice,
        success: function (res) { that.setData({ buthiddenPrice: false }); },
        fail: function (res) { that.setData({ buthiddenPrice: false }) },
        complete: function (res) { },
      })
    } else {
      if (Type == 3) {
        wx.navigateTo({
          url: 'scan?bId=' + bId,
          success: function (res) { that.setData({ buthiddenPrice: false }); },
          fail: function (res) { that.setData({ buthiddenPrice: false }) },
          complete: function (res) { },
        })
      } else {
        wx.navigateTo({
          url: 'priced?bId=' + bId,
          success: function (res) { that.setData({ buthiddenPrice: false }); },
          fail: function (res) { that.setData({ buthiddenPrice: false }) },
          complete: function (res) { },
        })
      }
    }

    // if (Type == 3 && paymentStatus != 2){   
    //   wx.navigateTo({
    //     url: 'scan?bId=' + bId,
    //     success: function (res) { that.setData({ buthiddenPrice: false }); },
    //     fail: function (res) { that.setData({ buthiddenPrice: false }) },
    //     complete: function (res) { },
    //      })

    // }else{
    //   wx.navigateTo({
    //     url: 'priced?bId=' + bId,
    //     success: function (res) { that.setData({ buthiddenPrice: false }); },
    //     fail: function (res) { that.setData({ buthiddenPrice: false }) },
    //     complete: function (res) { },
    //   })
    // }

  },

  //致电用户事件
  phonecallevent: function (e) {
    var that = this;
    // that.setData({ buthiddenTel: true });
    var tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel
    })

  },
  //取消订单事件
  ifCancel: function (e) {
    var that = this;
    var bId = e.currentTarget.dataset.bid;

    wx.showModal({
      // title: '提示',
      content: '确定取消该订单吗？',
      cancelText: '再等等',
      confirmColor: '#50BEC5',
      success: function (res) {

        if (res.confirm) {
          that.setData({ buthiddenCancel: true });
          wx.request({
            method: "POST",
            url: 'https://www.zaishengwang.com/wx/updateOrderStatus.do',
            dataType: 'json',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
              bId: bId,
              status: 3,
            },
            success: function (res) {
              if (res.data.msg != null) {
                that.onOrderInfo();
                that.setData({ buthiddenCancel: false });
              }
            },
            fail: function (error) {
              that.setData({ buthiddenCancel: false });
            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },

  //发布入口

  goFbSupply: function () {
    wx.navigateTo({
      url: '../supply/fb_supply?home=1',
    })
  },


  changeColor1: function () {
    var that = this;
    that.setData({
      ifbuthiddenV: false,
      flag: 1,
      checks: [{
        name: "货量少",
        value: '0',
        checked: false
      }, {
        name: "货质一般",
        value: '1',
        checked: false
      }, {
        name: "回收频率低",
        value: '2',
        checked: false
      }, {
        name: "不守信用",
        value: '3',
        checked: false
      }],
      comment: "一般用户"
    });
  },
  changeColor2: function () {
    var that = this;
    that.setData({
      ifbuthiddenV: false,
      flag: 2,
      checks: [{
        name: "货量少",
        value: '0',
        checked: false
      }, {
        name: "货质一般",
        value: '1',
        checked: false
      }, {
        name: "回收频率低",
        value: '2',
        checked: false
      }, {
        name: "不守信用",
        value: '3',
        checked: false
      }],
      comment: "一般用户"
    });
  },
  changeColor3: function () {
    var that = this;
    that.setData({
      ifbuthiddenV: false,
      flag: 3,
      checks: [{
        name: "货量较多",
        value: '0',
        checked: false
      }, {
        name: "货质优良",
        value: '1',
        checked: false
      }, {
        name: "回收有频率",
        value: '2',
        checked: false
      }, {
        name: "态度较好",
        value: '3',
        checked: false
      }],
      comment: "优质用户",
    });
  },
  changeColor4: function () {
    var that = this;
    that.setData({
      ifbuthiddenV: false,
      flag: 4,
      checks: [{
        name: "货量较多",
        value: '0',
        checked: false
      }, {
        name: "货质优良",
        value: '1',
        checked: false
      }, {
        name: "回收有频率",
        value: '2',
        checked: false
      }, {
        name: "态度较好",
        value: '3',
        checked: false
      }],
      comment: "优质用户",
    });
  },
  changeColor5: function () {
    var that = this;
    that.setData({
      ifbuthiddenV: false,
      flag: 5,
      checks: [{
        name: "货量大",
        value: '0',
        checked: false
      }, {
        name: "货质优",
        value: '1',
        checked: false
      }, {
        name: "回收频率高",
        value: '2',
        checked: false
      }, {
        name: "态度好",
        value: '3',
        checked: false
      }],
      comment: "VIP用户",
    });
  },

  clicks: function (e) {
   
    let index = e.currentTarget.dataset.index;
    let arrs = this.data.checks;
    let array = new Array;
    let text = e.currentTarget.dataset.text;
    if (arrs[index].checked == false) {
      arrs[index].checked = true;
      array.push(text);
    } else {
      arrs[index].checked = false;
    }
    this.setData({
      checks: arrs
    })
  },

  // 提交清空当前值
  bindSubmit: function () {
    var that = this;
    var checks = that.data.checks;
    var array = new Array;

    for (var i = 0; i < checks.length; i++) {
      if (checks[i].checked == true) {
        array.push(checks[i].name);
      }
    }
    that.setData({ arrayChecks: array })

    if (array.length <= 0) {
      wx.showToast({
        title: '评价类别必选',
        icon: 'none',
        duration: 1500,
      })
      return;
    }
    that.setData({ buthiddenV: true });
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/toSaveEvaluate.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        userId: that.data.userid,
        sendUserId: that.data.sendUserid,
        orderId: that.data.orderid,
        score: that.data.flag,
        label: that.data.arrayChecks
      },
      success: function (res) {
        var c = 2;
        that.setData({
          buthiddenV: false
        });
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500,
        })
        var intervalId = setInterval(function () {
          c = c - 1;
          if (c == 0) {
            clearInterval(intervalId);
            that.setData({ ifShowV: true, ifClick: true, checks: [], flag: 0, comment: "匿名评价用户" });
          }
        }, 1000)

      },
      fail: function (error) {
      }
    })

  },
  //去评价
  goValuation: function (e) {
    var that = this;
    var userid = e.target.dataset.userid;
    var sendUserid = e.target.dataset.receiptid;
    var orderid = e.target.dataset.ordernumber;
    that.setData({ ifShowV: false, userid: userid, sendUserid: sendUserid, orderid: orderid });
    wx.request({
      method: "POST",
      url: 'https://www.zaishengwang.com/wx/serchEvaluateList.do',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {

        sendUserId: sendUserid,
        orderId: orderid,

      },
      success: function (res) {
        var length = res.data.evaluateVo.length;
        if (length > 0) {
          that.setData({ ifbuthiddenV: true })
          var score = res.data.evaluateVo[0].score;
          if (score == 1 || score == 2) {
            that.setData({ comment: "一般用户" });
          } else if (score == 3 || score == 4) {
            that.setData({ comment: "优质用户" });
          } else if (score == 5) {
            that.setData({ comment: "VIP用户" });
          }

          var arr = (res.data.evaluateVo[0].label).split(",");
          for (var i = 0; i < arr.length; i++) {

            that.setData({
              ifClick: false,
              checks: that.data.checks.concat([
                {
                  value: i,
                  name: arr[i],
                  checked: true
                }
              ]),
              flag: score
            });

          }

        }

      },
      fail: function (error) {
      }
    })

  },
  //评价隐藏
  cancelV: function () {
    var that = this;
    that.setData({ ifShowV: true, ifClick: true, checks: [], flag: 0, comment: "匿名评价用户" })
  },

  noScroll: function () {
    //微信小程序有bind和catch两种事件绑定方法，bind事件绑定不会阻止冒泡事件向上冒泡，catch事件绑定可以阻止冒泡事件向上冒泡。我们使用catch绑定手指触摸事件，然后他的父节点就不会收到事件冒泡，这样就实现了禁止页面上下滑动
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      pageIndex: 1, // 每次触发下拉事件pageIndex=1
      wOrderVo: "",
    });
    that.onOrderInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (maxPageIndex < (that.data.pageIndex)) {
      return;
    }
    that.setData({
      pageIndex: that.data.pageIndex + 1,
    })
    
    // 上拉获取更多数据
    that.onOrderInfo();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})